import getpass
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
from utils.encrypt import encrypt_str
from utils.db import load_json_data

LOGIN_USER = None


@dataclass
class User:
    """User class to manage user information."""
    name: str
    password: str
    role: str


@lru_cache
def __load_user() -> dict[str, User]:
    """Load user data from a file."""
    file_path = Path(__file__).parent.parent / 'data' / "users.json"

    user_data = load_json_data(file_path)
    return {user["name"]: User(**user) for user in user_data}


# 管理员账号，暂时以这种形式管理
__ADMIN = __load_user()

def login():
    """用户登录"""
    username = input("用户名: ").strip()
    password = encrypt_str(input("密码: "))
    for user in __ADMIN.values():
        if user.name == username and password == user.password:
            print(f"\n{'-' * 30}\n欢迎回来，{username}!!!")
            global LOGIN_USER
            LOGIN_USER = username
            return True
    else:
        print("\n登录失败，请检查用户名密码")
        return False


def logout():
    """退出登录"""
    global LOGIN_USER
    LOGIN_USER = None
    print("已退出登录")


def is_login(func):
    """检查是否已登录"""
    def inner(*args, **kwargs):
        if LOGIN_USER is None:
            print("\n请先登录")
            return False
        return func(*args, **kwargs)
    return inner
